package server.controller;


import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import server.tool.RedisTool;
import server.tool.Tool;

import java.io.IOException;


// 媒体处理
@RequestMapping(method = {RequestMethod.GET}, value = "m")
@SuppressWarnings("unused")
@RestController
@CrossOrigin
public class MediaController {
    @Resource
    private Tool tool;
    @Resource
    private RedisTool redisTool;

    @GetMapping("/code")
    public void getVerityCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String ip = request.getRemoteAddr();
        if(StrUtil.isEmpty(ip)){
            response.sendError(500);
            return;
        }
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setContentType(MediaType.IMAGE_JPEG.toString());
        CircleCaptcha lineCaptcha= tool.makeCode(response);
        String code = lineCaptcha.getCode();
        if(tool.containsCode(ip)){
            redisTool.del_string(ip);
        }
        boolean isSave= tool.saveVerityCode(ip,code,60);
        lineCaptcha.write(response.getOutputStream());
    }
}
